package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.mq.listener.vo.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-06
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 批量插入设备数据
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //解析上报的数据 --在AmpqClient中实现
        //1.通过设备id查询设备 -注入IDeviceService或DeviceMapper
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        //2.设备是否存在 不存在-结束
        if (ObjectUtil.isEmpty(device)) {
            log.warn("设备不存在, {}", iotId);
            return;
        }
        //3.构建设备数据，添加到集合中 --循环构建（先循环services，再循环物模型）
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        if (CollUtil.isEmpty(services)) {
            log.warn("设备数据为空, {}", iotId);
            return;
        }

        List<DeviceData> deviceDataList = new ArrayList<>();
        //获取到设备上报的数据，一个设备可以有多个service
        services.forEach(s -> {
            // 将所有数据都装入到map中
            Map<String, Object> properties = s.getProperties();
            if (CollUtil.isEmpty(properties)) {
                return;
            }

            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();


            //循环properties
            properties.forEach((k, v) -> {
                //将数据封装到DeviceData, 拷贝
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                //设置其它字段
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(alarmTime);
                //添加到List集合中
                deviceDataList.add(deviceData);

            });

        });

        //4.批量保存
        saveBatch(deviceDataList);

        //存储到redis中deviceDataList
        //hash 结构来进行存储  大key  小key  value
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(deviceDataList));
    }




    /**
     * 删除设备数据，只保留最近两周的数据
     * 定时任务，每天删除 > 15天的数据
     */
    @Override
    public void deleteOldData() {
        //计算15天前的时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime fifteenDaysAgo = now.minus(15, ChronoUnit.DAYS);

        //计算30分
        // LocalDateTime fifteenDaysAgo = now.minus(30, ChronoUnit.MINUTES);

        //计算1h
        // LocalDateTime fifteenDaysAgo = now.minus(1, ChronoUnit.HOURS);

        //构建查询条件 alarm_time > 15
        QueryWrapper<DeviceData> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("alarm_time", fifteenDaysAgo);

        //执行删除操作
        int result = baseMapper.delete(queryWrapper);
        log.info("删除了{}条数据", result);

    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

}
